<template>
    <audio
    @error="errorHandler"
    @canplay="getDuration"
    ref="audio"
    :src="_src"
    @ended="onEnd"
    autoplay="true"
    loop="true"
    ></audio>
</template>
<script>
export default {
  data () {
    return {
      playing: false,
      playIndex: 0,
      duration: 0
    }
  },
  props: {
    urls: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    _src() {
      const { urls, playIndex } = this
      if (urls.length) {
        return urls[playIndex].filePath;
      }
    }
  },
  mounted () {
  },
  methods: {
    getDuration() {
      this.duration = this.$refs.audio.duration
    },
    onEnd() {
      this.playing = false
      const { playIndex, urls } = this
      if (playIndex < urls.length - 1) {
        this.playIndex = playIndex + 1
        this.$nextTick(() => {
          this.play()
        })
      }
    },
    errorHandler() {
      this.onEnd()
    },
    play() {
      if (this.playing) {
        this.pause()
      } else {
        this.$refs['audio'].play()
        this.playing = true
      }
    },
    pause() {
      this.$refs['audio'].pause()
      this.playing = false
    }
  }
}
</script>
<style lang="scss" scoped>
.audio-player {
  position: absolute;
  width: 24px;
  height: 24px;
  background: transparent;
  border-radius: 50%;
  background: url('../assets/img/icon-audio-player.png') no-repeat center;
  background-size: 100% 100%;
  cursor: pointer;
  z-index: 99;
}
@-webkit-keyframes play {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}
.play {
  -webkit-animation:myRotate 10s linear infinite;
  animation:myRotate 10s linear infinite;
}
@-webkit-keyframes myRotate{
    0%{ -webkit-transform: rotate(0deg);}
    50%{ -webkit-transform: rotate(180deg);}
    100%{ -webkit-transform: rotate(360deg);}
}
@keyframes myRotate{
    0%{ -webkit-transform: rotate(0deg);}
    50%{ -webkit-transform: rotate(180deg);}
    100%{ -webkit-transform: rotate(360deg);}
}
</style>
